<?php

namespace app\admin\controller;

use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Refund extends AdminControl
{
    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/refund.lang.php');
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/vrorder.lang.php');
        //向模板页面输出退款退货状态
        $this->getRefundStateArray();
    }

    function getRefundStateArray($type = 'all')
    {
        $state_array = array(
            '1' => lang('refund_state_confirm'), '2' => lang('refund_state_yes'), '3' => lang('refund_state_no')
        ); //卖家处理状态:1为待审核,2为同意,3为不同意
        $this->assign('state_array', $state_array);

        $admin_array = array(
            '1' => lang('admin_state_1'), '2' => lang('admin_state_2'), '3' => lang('admin_state_3')
        ); //确认状态:1为买家或卖家处理中,2为待平台管理员处理,3为退款退货已完成
        $this->assign('admin_array', $admin_array);

        $state_data = array(
            'seller' => $state_array, 'admin' => $admin_array
        );
        if ($type == 'all') {
            return $state_data; //返回所有
        }
        return $state_data[$type];
    }

    /**
     * 退款待处理列表
     */
    public function refund_manage()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['refund_state'] = '2'; //状态:1为处理中,2为待管理员处理,3为已完成

        $keyword_type = array('order_sn', 'refund_sn', 'store_name', 'buyer_name', 'goods_name');
        $key = input('get.key');
        $type = input('get.type');
        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }
        $add_time_from = input('get.add_time_from');
        $add_time_to = input('get.add_time_to');
        if (trim($add_time_from) != '' || trim($add_time_to) != '') {
            $add_time_from = strtotime(trim($add_time_from));
            $add_time_to = strtotime(trim($add_time_to));
            if ($add_time_from !== false || $add_time_to !== false) {
                $condition['add_time'] = array('between', array($add_time_from, $add_time_to));
            }
        }
        $refund_list = $refundreturn_model->getRefundList($condition, 10);
        //p($refund_list);die;
        $this->assign('show_page', $refundreturn_model->page_info->render());
        $this->assign('refund_list', $refund_list);
        $this->setAdminCurItem('refund_manage');
        $this->assign('type', $type);
        $this->assign('add_time_from', $add_time_from);
        $this->assign('add_time_to', $add_time_to);
        return $this->fetch('refund_manage');
    }

    /**
     * 退款所有记录
     */
    public function refund_all()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $keyword_type = array('order_sn', 'refund_sn', 'store_name', 'buyer_name', 'goods_name');
        $key = input('get.key');
        $type = input('get.type');
        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }
        $add_time_from = input('get.add_time_from');
        $add_time_to = input('get.add_time_to');
        if (trim($add_time_from) != '' || trim($add_time_to) != '') {
            $add_time_from = strtotime(trim($add_time_from));
            $add_time_to = strtotime(trim($add_time_to));
            if ($add_time_from !== false || $add_time_to !== false) {
                $condition['add_time'] = array('between', array($add_time_from, $add_time_to));
            }
        }
        $refund_list = $refundreturn_model->getRefundList($condition, 10);
        $this->assign('show_page', $refundreturn_model->page_info->render());
        $this->assign('refund_list', $refund_list);
        $this->assign('type', $type);
        $this->assign('add_time_from', $add_time_from);
        $this->assign('add_time_to', $add_time_to);
        $this->setAdminCurItem('refund_all');
        return $this->fetch('refund_all');
    }

    /**
     * 发票所有记录
     */
    public function invoice_all()
    {
        $order_model = model('order');
        $condition = array();
        $keyword_type = array('order_sn', 'refund_sn', 'store_name', 'buyer_name', 'goods_name');
        $key = input('get.key');
        $type = input('get.type');
        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }
        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_app_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2', '3', '4'))) {
            $condition['ds_app_order.order_status'] = $order_state;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_app_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_app_order.create_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        // $condition['ds_app_order.is_cancel'] = 0;
        if (isset($condition['ds_app_order.order_status']) && $condition['ds_app_order.order_status'] == 4) {
            $condition['ds_app_order.order_status'] = 1;
            $condition['ds_app_order.refund_price'] = 1;
        }
        $condition['app_order.invoice_status'] = 2;
        $order_list = $order_model->getInvoiceList($condition, 10);
        //p($refund_list);die;
        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('refund_list', $order_list);
        $this->assign('type', $type);
        $this->assign('query_start_time', $query_start_time);
        $this->assign('query_end_time', $query_end_time);
        $this->setAdminCurItem('invoice_all');
        return $this->fetch('invoice_all');
    }

    /**
     * 商城 项目定制 发票查看订单
     *
     */
    public function show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        // $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));
        $order_info = $order_model->getOrderInfo(array('app_order_id' => $order_id), array('order_goods', 'order_common', 'store'));

        if (!empty($order_info['apporder_id'])) {
            //获取大订单详情
            $app_order_info = db('app_order')->where(['app_order_id' => $order_info['apporder_id']])->find();


            $tblname = 'invoice';
            $field = 'a.*,b.name,b.type,b.billing_type';
            $where['a.app_order_id'] = $order_id;
            $where['b.status'] = 1;
            $where['b.is_del'] = 0;
            $invoice_info = db($tblname . ' a')->join('__INVOICE_TYPE__ b', 'a.invoice_type_id=b.id')->where($where)->field($field)->find();
            $this->assign('app_order_info', $app_order_info);
            $this->assign('invoice_info', $invoice_info);
            //            $this->assign('invoice_type_info', $invoice_type_info);
        }
        #判断项目定制
        if ($order_info['app_order_type'] == 2) {
            $project_info = db('orderproject')->where(['order_id' => $order_info['app_order_project_id']])->find();
            $this->assign('project_info', $project_info);
        }


        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }
        $this->assign('goods_status', array('0' => '正常', '1' => '退款待处理', '2' => '退货待处理', '3' => '换货待处理', '4' => '退货成功', '5' => '评价成功', '6' => '退款成功', '7' => '供应商处理换货成功', '8' => '运营商处理退货同意', '9' => '运营商处理换货同意'));
        $this->assign('order_info', $order_info);

        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        return $this->fetch('show_order');
    }

    /**
     * 服务单 发票查看订单
     *
     */
    public function service_show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');

        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));
        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }
        $this->assign('goods_status', array('0' => '正常', '1' => '退款待处理', '2' => '退货待处理', '3' => '换货待处理', '4' => '退货成功', '5' => '评价成功', '6' => '退款成功', '7' => '供应商处理换货成功', '8' => '运营商处理退货同意', '9' => '运营商处理换货同意'));
        $this->assign('order_info', $order_info);

        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        return $this->fetch('service_show_order');
    }

    /**
     * 退款查看订单
     *
     */
    public function return_show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));


        $app_order_info = [
            'invoice_status' => ''
        ];

        if (!empty($order_info['apporder_id'])) {
            //获取大订单详情
            $app_order_info = db('app_order')->where(['app_order_id' => $order_info['apporder_id']])->find();


            $tblname = 'invoice';
            $field = 'a.*,b.name,b.type,b.billing_type';
            $where['a.app_order_id'] = $order_id;
            $where['b.status'] = 1;
            $where['b.is_del'] = 0;
            $invoice_info = db($tblname . ' a')->join('__INVOICE_TYPE__ b', 'a.invoice_type_id=b.id')->where($where)->field($field)->find();
            $this->assign('app_order_info', $app_order_info);
            $this->assign('invoice_info', $invoice_info);
            //            $this->assign('invoice_type_info', $invoice_type_info);
        }

        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }
        $this->assign('goods_status', array('0' => '正常', '1' => '退款待处理', '2' => '退货待处理', '3' => '换货待处理', '4' => '退货成功', '5' => '评价成功', '6' => '退款成功', '7' => '供应商处理换货成功', '8' => '运营商处理退货同意', '9' => '运营商处理换货同意'));
        $this->assign('order_info', $order_info);

        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        return $this->fetch('return_show_order');
    }

    /**
     * 退款处理页
     *
     */
    public function edit()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['refund_id'] = intval(input('param.refund_id'));
        $refund_list = $refundreturn_model->getRefundList($condition);
        $refund = $refund_list[0];
        if (request()->isPost()) {
            $refund_id = intval(input('param.refund_id'));
            if ($refund_id <= 0) {
                $this->error('操作失败');
            }
            $refund_info = db('refundreturn')->where('refund_id', $refund_id)->find();
            if (empty($refund_id)) {
                $this->error('操作失败');
            }
            $post_data = input('post.');
            if ($refund_info['refund_type'] == 1) {
                #子订单退款
                db('order')->where('order_id', $refund_info['order_id'])->data(['refund_state' => 3])->update();
                db('ordergoods')->where('order_id', $refund_info['order_id'])->data(['return_status' => 6])->update();
                $arr = db('refundreturn')->where('refund_id', $refund_info['refund_id'])->data(['refund_state' => 3])->update();

                #退款成功更新大订单表的退款金额refund_amount
                db('app_order')->where(['app_order_id' => $refund_info['app_order_id']])->update(['app_return_price' => $refund_info['refund_amount']]);

                check_big_order_status($refund['buyer_id'], $refund['app_order_id']);

                if ($arr) {
                    #推送
                    $member_info = db('member')
                        ->where(['member_id' => $refund_info['buyer_id']])
                        ->find();
                    #通知内容
                    $notif_data = [
                        'order_id' => $refund_info['order_id'],
                        'notif_title' => '退款通知',
                        'notif_content' =>  '提交的退款申请已审核，审核备注：' . $post_data['admin_message'],
                        'member_id' => $member_info['member_id'],
                        'member_name' => $member_info['member_name'],
                    ];
                    model('points')->saveAfficeslog(0, 0, $notif_data); #客户
                    pushMessageToSingle('退款通知', $member_info['clientid'], '您申请的退款申请已审核，请及时查看！');

                    // 发送买家消息
                    $param = array();
                    $param['code'] = 'refund_return_notice';
                    $param['member_id'] = $refund['buyer_id'];
                    $param['param'] = array(
                        'refund_url' => url('Home/memberrefund/view', array('refund_id' => $refund['refund_id'])),
                        'refund_sn' => $refund['refund_sn']
                    );
                    \mall\queue\QueueClient::push('sendMemberMsg', $param);
                    $this->log('退款确认，退款编号' . $refund['refund_sn']);
                    dsLayerOpenSuccess('操作成功');
                } else {
                    dsLayerOpenSuccess('操作失败');
                }
            } elseif ($refund_info['refund_type'] == 2) {
                #退货 7.5 21 
                db('ordergoods')->where('rec_id', $refund_info['order_goods_id'])->data(['return_status' => 4,'platform_refund'=>$post_data['refund_amount']])->update();
                $arr = db('refundreturn')->where('refund_id', $refund_info['refund_id'])->data(['refund_state' => 3, 'admin_message' => $post_data['admin_message'], 'refund_amount' => $post_data['refund_amount']])->update();

                #退款成功更新大订单表的退款金额refund_amount
                db('app_order')->where(['app_order_id' => $refund_info['app_order_id']])->update(['app_return_price' => $refund_info['refund_amount']]);

                check_big_order_status($refund['buyer_id'], $refund['app_order_id']);
                if ($arr) {
                    #推送
                    $member_info = db('member')
                        ->where(['member_id' => $refund_info['buyer_id']])
                        ->find();
                    #通知内容
                    $notif_data = [
                        'order_id' => $refund_info['order_id'],
                        'notif_title' => '退货通知',
                        'notif_content' =>  '提交的退货申请已审核，审核备注：' . $post_data['admin_message'],
                        'member_id' => $member_info['member_id'],
                        'member_name' => $member_info['member_name'],
                    ];
                    model('points')->saveAfficeslog(0, 0, $notif_data); #客户
                    pushMessageToSingle('退货通知', $member_info['clientid'], '您申请的退货申请已审核，请及时查看！');

                    // 发送买家消息
                    $param = array();
                    $param['code'] = 'refund_return_notice';
                    $param['member_id'] = $refund['buyer_id'];
                    $param['param'] = array(
                        'refund_url' => url('Home/memberrefund/view', array('refund_id' => $refund['refund_id'])),
                        'refund_sn' => $refund['refund_sn']
                    );
                    \mall\queue\QueueClient::push('sendMemberMsg', $param);
                    $this->log('退款确认，退款编号' . $refund['refund_sn']);
                    dsLayerOpenSuccess('操作成功');
                } else {
                    dsLayerOpenSuccess('操作失败');
                }
            }
        }
        $this->assign('refund', $refund);
        $info['buyer'] = array();
        // if (!empty($refund['pic_info'])) {
        //     $info = unserialize($refund['pic_info']);
        // }
        $this->assign('pic_list', $info['buyer']);

        //获取图片
        $apply_images = json_decode($refund['pic_info'], true);
        $this->assign('apply_images', $apply_images);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);

        return $this->fetch('edit');
    }

    /**
     * 退款
     *
     */
    public function app_order_edit()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['refund_id'] = intval(input('param.refund_id'));
        $app_order_id = intval(input('param.app_order_id'));
        $refund_list = $refundreturn_model->getRefundList($condition);
        $refund = $refund_list[0];
        if (request()->isPost()) {
            $post_data = input('post.');
            $refund_id = intval(input('param.refund_id'));
            if ($refund_id <= 0) {
                $this->error('操作失败');
            }
            $refund_info = db('refundreturn')->where('refund_id', $refund_id)->find();
            if (empty($refund_id)) {
                $this->error('操作失败');
            }
            if ($refund_info['refund_type'] == 4) {
                #退款
                db('app_order')->where('app_order_id', $app_order_id)->data(['order_status' => 4])->update();
                db('ordergoods')->where('order_id', $refund_info['order_id'])->data(['return_status' => 6])->update();
                $arr = db('refundreturn')->where('refund_id', $refund_info['refund_id'])->data(['refund_state' => 3, 'admin_message' => $post_data['admin_message'], 'refund_amount' => $post_data['refund_amount']])->update();
                if ($arr) {
                    // 发送买家消息
                    $param = array();
                    $param['code'] = 'refund_return_notice';
                    $param['member_id'] = $refund['buyer_id'];
                    $param['param'] = array(
                        'refund_url' => url('Home/memberrefund/view', array('refund_id' => $refund['refund_id'])),
                        'refund_sn' => $refund['refund_sn']
                    );
                    \mall\queue\QueueClient::push('sendMemberMsg', $param);
                    $this->log('退款确认，退款编号' . $refund['refund_sn']);
                    dsLayerOpenSuccess('操作成功');
                } else {
                    dsLayerOpenSuccess('操作失败');
                }
            }
        }
        $this->assign('refund', $refund);
        $info['buyer'] = array();
        // if (!empty($refund['pic_info'])) {
        //     $info = unserialize($refund['pic_info']);
        // }
        $this->assign('pic_list', $info['buyer']);

        //获取图片
        $apply_images = json_decode($refund['pic_info'], true);
        $this->assign('apply_images', $apply_images);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);

        return $this->fetch('app_order_edit');
    }

    /**
     * 退款记录查看页
     *
     */
    public function view()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['refund_id'] = intval(input('param.refund_id'));
        $refund_list = $refundreturn_model->getRefundList($condition);
        $refund = $refund_list[0];
        $this->assign('refund', $refund);
        $info['buyer'] = array();
        if (!empty($refund['pic_info'])) {
            $info = unserialize($refund['pic_info']);
        }
        $this->assign('pic_list', $info['buyer']);
        return $this->fetch('view');
    }

    /**
     * 退换货原因
     */
    public function reason()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();

        if (trim(input('param.title'))) {
            $title_name = input('param.title');
            $condition['reason_info'] = array('like', "%$title_name%");
        }
        $type = intval(input('param.type'));
        if ($type) {
            $condition['type'] = $type;
        }

        $status = intval(input('param.status'));
        if ($status) {
            if ($status == 2) {
                $condition['status'] = 0;
            } else {
                $condition['status'] = $status;
            }
        }
        /** 新增限制条件
         * */
        $condition['is_del'] = 0;
        $reason_list = $refundreturn_model->getReasonList($condition, 10);
        $this->assign('reason_list', $reason_list);
        $this->assign('show_page', $refundreturn_model->page_info->render());

        $this->assign('title_name', input('param.title'));
        $this->assign('type', $type);
        $this->assign('status', $status);

        $this->setAdminCurItem('reason');
        return $this->fetch('reason');
    }

    /**
     * 新增退款退货原因
     */
    public function add_reason()
    {
        $refundreturn_model = model('refundreturn');
        if (request()->post()) {
            $reason_array = array();
            $reason_array['reason_info'] = input('post.reason_info');
            $reason_array['reason_sort'] = intval(input('post.reason_sort'));
            $reason_array['type'] = input('post.type');
            $reason_array['status'] = intval(input('post.status'));
            $reason_array['reason_updatetime'] = time();
            //p($reason_array);die;
            $state = $refundreturn_model->addReason($reason_array);
            if ($state) {
                $this->log('新增退款退货原因，编号' . $state);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                dsLayerOpenSuccess('添加失败');
            }
        }
        return $this->fetch('add_reason');
    }

    /**
     * 编辑退款退货原因
     *
     */
    public function edit_reason()
    {
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['reason_id'] = intval(input('param.reason_id'));
        $reason_list = $refundreturn_model->getReasonList($condition);
        $reason = $reason_list[$condition['reason_id']];
        if (request()->post()) {
            $reason_array = array();
            $reason_array['reason_info'] = input('post.reason_info');
            $reason_array['reason_sort'] = intval(input('post.reason_sort'));
            $reason_array['type'] = input('post.type');
            $reason_array['status'] = intval(input('post.status'));
            $reason_array['reason_updatetime'] = time();
            $state = $refundreturn_model->editReason($condition, $reason_array);
            if ($state) {
                $this->log('编辑退款退货原因，编号' . $condition['reason_id']);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        }
        $this->assign('reason', $reason);
        return $this->fetch('edit_reason');
    }

    /**
     *  退换货理由上下架
     */

    public function status()
    {
        $id = trim(input('param.id'));
        $status = trim(input('param.status'));
        $info = db('refundreason')->where('reason_id', $id)->where('is_del', 0)->find();
        if ($status == 0) {
            #操作下架 判断是否是最后一条
            $count = db('refundreason')->where('status', 1)->where('is_del', 0)->where('type', $info['type'])->count();
            if ($count == 1) {
                ds_json_encode(10001, '不能停用最后一条原因');
            }
        }
        if (empty($id)) {
            ds_json_encode(10001, '操作失败');
        }

        if ($status == $info['status']) {
            ds_json_encode(10001, '操作失败');
        }
        $data = array();
        $data['status'] = $status;
        $rs = db('refundreason')->where('reason_id', $id)->data($data)->update();
        if ($rs) {
            $this->log(lang('ds_del') . '退换货理由上下架' . '[ID:' . $id . ']');
            ds_json_encode(10000, '操作成功');
        } else {
            ds_json_encode(10001, '操作失败');
        }
    }

    /**
     * 删除退款退货原因
     *
     */
    public function del_reason()
    {
        $reason_id = input('param.reason_id');
        if (empty($reason_id)) {
            ds_json_encode(10001, '操作失败');
        }
        $info = db('refundreason')->where('is_del', 0)->where('reason_id', $reason_id)->find();
        if (empty($info)) {
            ds_json_encode(10001, '操作失败');
        }
        if ($info['status'] == 1) {
            ds_json_encode(10001, '请先停用');
        }
        #判断是否是最后一条
        $count = db('refundreason')->where('type', $info['type'])->count();
        if ($count == 1) {
            ds_json_encode(10001, '不能删除该类型下最后一条原因');
        }
        $rs = db('refundreason')->where('reason_id', $reason_id)->data(['is_del' => 1])->update();
        if ($rs) {
            $this->log('删除退款退货原因，编号' . $reason_id);
            ds_json_encode('10000', lang('ds_common_del_succ'));
        } else {
            ds_json_encode('10001', lang('ds_common_del_fail'));
        }
    }

    /**
     * 导出
     *
     */
    public function export_step1()
    {

        $refundreturn_model = model('refundreturn');
        $condition = array();

        $keyword_type = array('order_sn', 'refund_sn', 'store_name', 'buyer_name', 'goods_name');
        $key = input('get.key');
        $type = input('get.type');
        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }
        $add_time_from = input('get.add_time_from');
        $add_time_to = input('get.add_time_to');
        if (trim($add_time_from) != '' || trim($add_time_to) != '') {
            $add_time_from = strtotime(trim($add_time_from));
            $add_time_to = strtotime(trim($add_time_to));
            if ($add_time_from !== false || $add_time_to !== false) {
                $condition['add_time'] = array('between', array($add_time_from, $add_time_to));
            }
        }
        if (!is_numeric(input('param.curpage'))) {
            $count = $refundreturn_model->getRefundCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) { //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                $this->assign('export_list', $export_list);
                return $this->fetch('/public/excel');
            } else { //如果数量小，直接下载
                $data = $refundreturn_model->getRefundList($condition, '', '*', 'refund_id desc', self::EXPORT_SIZE);
                $this->createExcel($data);
            }
        } else { //下载
            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $refundreturn_model->getRefundList($condition, '', '*', 'refund_id desc', "{$limit1},{$limit2}");
            $this->createExcel($data);
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('ds_order_sn'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('ds_refund_sn'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('ds_store_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('ds_goods_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('ds_buyer_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_tk_order_add_time'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_tk_order_refund'));
        //data
        foreach ((array) $data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => 'DS' . $v['order_sn']);
            $tmp[] = array('data' => $v['refund_sn']);
            $tmp[] = array('data' => $v['store_name']);
            $tmp[] = array('data' => $v['goods_name']);
            $tmp[] = array('data' => $v['buyer_name']);
            $tmp[] = array('data' => date('Y-m-d H:i:s', $v['add_time']));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['refund_amount']));
            $excel_data[] = $tmp;
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('exp_tk_refund'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset(lang('exp_tk_refund'), CHARSET) . input('param.curpage') . '-' . date('Y-m-d-H', time()));
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'refund_manage', 'text' => '退货申请', 'url' => url('Refund/refund_manage')
            ),
            array(
                'name' => 'refund_all', 'text' => '退款记录', 'url' => url('Refund/refund_all')
            ),
            //  array(
            //     'name' => 'invoice_all', 'text' => '发票记录', 'url' => url('Refund/invoice_all')
            // ),
            array(
                'name' => 'reason', 'text' => lang('refund_return_reason'), 'url' => url('Refund/reason')
            ),
        );
        if (request()->action() == 'reason') {
            $menu_array[] = [
                'name' => 'add_reason', 'text' => lang('add_reason'), 'url' => "javascript:dsLayerOpen('" . url('Refund/add_reason') . "','" . lang('add_reason') . "')"
            ];
        }
        return $menu_array;
    }
}
